package org.rcy.ruicingmarket.common.utils;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;

import java.io.IOException;

public class JsonUtils {
	
	private static ObjectMapper mapper = new ObjectMapper();
	static{
		mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
		mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
		mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
		//根据属性序列化
		mapper.setVisibility(
				mapper.getSerializationConfig().
				getDefaultVisibilityChecker().
				withFieldVisibility(JsonAutoDetect.Visibility.ANY).
				withGetterVisibility(JsonAutoDetect.Visibility.NONE));
		
		SimpleModule module = new SimpleModule();
		module.addSerializer(Long.class, new ToStringSerializer());
		mapper.registerModule(module);
	}
	
	public static String toJson(Object object) throws IOException {
		return mapper.writeValueAsString(object);
	}
	
	public static String toJsonPretty(Object object) throws IOException {
		return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
	}

	public static <T> T parseObject(String text, Class<? extends T> clazz) throws IOException {
		return mapper.readValue(text, clazz);
	}

	public static byte[] toJsonBytes(Object object) throws IOException {
		return mapper.writeValueAsBytes(object);
	}
	
	public static <T> T parseArray(String text, TypeReference<T> typeReference) throws IOException {
		return mapper.readValue(text,typeReference);
	}

}